package com.zhentao.controller;

import com.zhentao.common.Result;
import com.zhentao.service.RecommendService;
import com.zhentao.vo.RecommendUserVO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.zhentao.dto.UserSearchQuery;

import javax.annotation.Resource;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/recommend")
public class RecommendController {

    @Resource
    private RecommendService recommendService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/users")
    public Result<List<RecommendUserVO>> getRecommendedUsers(
            @RequestParam Integer userId,
            @RequestParam(required = false, defaultValue = "1") Integer oppoOnly,
            @RequestParam(required = false, defaultValue = "50") Integer limit,
            @RequestParam(required = false, defaultValue = "0") Integer offset
    ) {
        try {
            List<RecommendUserVO> list = recommendService.getRecommendedUsers(userId, oppoOnly, limit);
            return Result.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取推荐用户失败: " + e.getMessage());
        }
    }

    // 用户行为反馈：喜欢/不喜欢
    @RequestMapping(value = "/feedback", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<String> feedback(
            @RequestParam Integer userId,
            @RequestParam Integer targetUserId,
            @RequestParam String type // like | dislike
    ) {
        try {
            String likeKey = likeKey(userId);
            String dislikeKey = dislikeKey(userId);

            if ("like".equalsIgnoreCase(type)) {
                // 记录喜欢，并从不喜欢集合移除（幂等）
                stringRedisTemplate.opsForSet().add(likeKey, String.valueOf(targetUserId));
                stringRedisTemplate.opsForSet().remove(dislikeKey, String.valueOf(targetUserId));
            } else if ("dislike".equalsIgnoreCase(type)) {
                stringRedisTemplate.opsForSet().add(dislikeKey, String.valueOf(targetUserId));
                stringRedisTemplate.opsForSet().remove(likeKey, String.valueOf(targetUserId));
            } else {
                return Result.error(400, "type only supports like|dislike");
            }

            System.out.println("✅ feedback: user=" + userId + ", target=" + targetUserId + ", type=" + type);
            return Result.success("ok", "ok");
        } catch (Exception e) {
            // Redis 操作失败，仍然返回成功（优雅降级）
            System.err.println("⚠️ Redis 操作失败，但反馈已记录: " + e.getMessage());
            System.out.println("✅ feedback (Redis不可用): user=" + userId + ", target=" + targetUserId + ", type=" + type);
            return Result.success("ok", "ok (Redis unavailable)");
        }
    }

    // 曝光上报：便于重排/多样性控制
    @RequestMapping(value = "/exposure", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<String> exposure(
            @RequestParam Integer userId,
            @RequestParam String shownUserIds // 逗号分隔
    ) {
        System.out.println("exposure: user=" + userId + ", shown=" + shownUserIds);
        return Result.success("ok", "ok");
    }

    // 查询双方关系：like / dislike / none
    @GetMapping("/relation")
    public Result<Map<String, Object>> relation(
            @RequestParam Integer userId,
            @RequestParam Integer targetUserId
    ) {
        try {
            boolean liked = Boolean.TRUE.equals(
                    stringRedisTemplate.opsForSet().isMember(likeKey(userId), String.valueOf(targetUserId))
            );
            boolean disliked = Boolean.TRUE.equals(
                    stringRedisTemplate.opsForSet().isMember(dislikeKey(userId), String.valueOf(targetUserId))
            );
            String status = liked ? "like" : (disliked ? "dislike" : "none");

            // 是否互相喜欢（匹配）
            boolean mutualLike = liked && Boolean.TRUE.equals(
                    stringRedisTemplate.opsForSet().isMember(likeKey(targetUserId), String.valueOf(userId))
            );

            Map<String, Object> data = new HashMap<>();
            data.put("status", status);
            data.put("mutualLike", mutualLike);
            return Result.success(data);
        } catch (Exception e) {
            // Redis 不可用时返回默认状态
            System.err.println("⚠️ Redis 查询失败: " + e.getMessage());
            Map<String, Object> data = new HashMap<>();
            data.put("status", "none");
            data.put("mutualLike", false);
            return Result.success(data);
        }
    }

    private String likeKey(Integer userId) {
        return "rec:like:user:" + userId;
    }

    private String dislikeKey(Integer userId) {
        return "rec:dislike:user:" + userId;
    }

    @PostMapping("/search")
    public Result<java.util.List<RecommendUserVO>> searchByRules(@RequestBody com.zhentao.dto.UserSearchQuery q) {
        try {
            java.util.List<RecommendUserVO> list = recommendService.searchByRules(q);
            return Result.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("规则检索失败: " + e.getMessage());
        }
    }

    // 地区接口，供前端联动选择

    @GetMapping("/area/cities")
    public Result<java.util.List<java.util.Map<String,Object>>> cities() {
        java.util.List<com.zhentao.pojo.City> cities = recommendService.getAllCities();
        java.util.List<java.util.Map<String,Object>> list = new java.util.ArrayList<>();
        for (com.zhentao.pojo.City c : cities) {
            list.add(mapOf("id", c.getId(), "name", c.getName()));
        }
        return Result.success(list);
    }

    @GetMapping("/area/areas")
    public Result<java.util.List<java.util.Map<String,Object>>> areas(@RequestParam Integer cityId) {
        java.util.List<com.zhentao.pojo.Area> areas = recommendService.getAreasByCity(cityId);
        java.util.List<java.util.Map<String,Object>> list = new java.util.ArrayList<>();
        for (com.zhentao.pojo.Area a : areas) {
            list.add(mapOf("id", a.getId(), "name", a.getName()));
        }
        return Result.success(list);
    }

    private java.util.Map<String,Object> mapOf(String k1, Object v1, String k2, Object v2) {
        java.util.Map<String,Object> m = new java.util.HashMap<>();
        m.put(k1, v1); m.put(k2, v2); return m;
    }

}


